# -*- coding: utf8 -*-
import logging
import re
import common

site_index = 'metrolyrics'
site_keyword = 'metrolyrics'
site_url = 'http://www.metrolyrics.com/'
test_url = 'http://www.metrolyrics.com/we-belong-together-lyrics-mariah-carey.html'

def get_lyric(url):
    encoding = 'utf8'

    logging.debug('url [%s]' % (url, ))

    bytes = common.get_url_content(url)
    html = bytes.decode(encoding, 'ignore')

    pattern = 'rm_artist = "(.*)"'
    artist = common.get_first_group_by_pattern(html, pattern)

    pattern = 'rm_songtitle = "(.*)"'
    title = common.get_first_group_by_pattern(html, pattern)

    logging.debug('artist [%s], title [%s]' % (artist, title, ))

    pattern = '<div id="lyrics">(.*)</div>'
    rawLyric = common.get_first_group_by_pattern(html, pattern)

    rawLyric = rawLyric.replace('<br />', '')

    lyric = u'%s\n\nArtist: %s\n\n\n%s' % (title, artist, rawLyric)

    # convert &#115; to unicode character
    def code_point_to_char(matchobj):
        if matchobj.group(1):
            return unichr(int(matchobj.group(1)))
    pattern = '&#([0-9]+);'
    lyric = re.sub(pattern, code_point_to_char, lyric)

    return lyric

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    url = test_url
    print url
    lyric = get_lyric(url)
    print repr(lyric) 
